const cron = require('node-cron');
const {motionRunner} = require("../services/changeService");
const moment = require('moment');
const {randomInt} = require("crypto");
// const cron = require('cron');


// 5秒 * * * * * */5  */10 * * * * *
// 每日八点到九点 周一到周六
const expression = '33-35 11 * * 1-6';
let users = [{
    username: "3210059822@qq.com",
    password: "yuekaizheng123",
    // step_start: 2766,
    // step_end: 2968,
    step_start: 8057,
    step_end: 12573,
    // time_start_new: "11:05",
    // time_end_new: "11:30",
}]


function realCornExecSingle(i, hours, minutes,ex) {

    console.log("执行时间：", hours, minutes);


    users.forEach(a => {

        let exec = ex || shouldExecuteSingle(a);
        console.log("是否执行 ：", exec);
        if (!exec) {
            return;
        }
        const stepRandom = randomInt(a.step_start, a.step_end)
        console.log("账号：", a.username, " 步数：", stepRandom)
        motionRunner(a.username, a.password, stepRandom).then(res => {
            console.log("执行成功", a.username);
        }).catch(res => {
            console.log("---------------", res)
        })

    })
}


// 定义一个任务，每隔一分钟执行一次  */1 * * * *  * * * * *

// const expression = '* 20 * * *';

function startTask() {
    console.log('corn start begin')
    cron.schedule(expression, () => {
        // 获取当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');

        // 打印日期和时间
        console.log(`------- [${moment().format('YYYY-MM-DD HH:mm:ss')}] ------- 定时任务启动 -------`);
        for (let i = 0; i < 1; i++) {
            realCornExecSingle(i, hours, minutes,true);
        }

    });
    console.log('corn start end')
}


function shouldExecuteSingle(data) {

    const startTime = moment(data.time_start_new, 'HH:mm');
    const endTime = moment(data.time_end_new, 'HH:mm');
    // const startTime = data.time_start_new;
    // const endTime = data.time_end_new;
    const currentTime = moment();
    console.log("当前时间和结束时间差') ", Math.abs(endTime.diff(currentTime, 'minutes')), startTime, endTime, currentTime, data.username)
    // 如果结束时间距离当前时间小于五分钟，则直接返回 true
    if (Math.abs(endTime.diff(currentTime, 'minutes')) <= 5) {
        return true;
    }
    // 执行概率提高
    const diffMinutes = Math.abs(endTime.diff(currentTime, 'minutes'));
    // 计算执行的概率
    const probability = 1 / diffMinutes;
    // 生成一个 [0, 1) 区间的随机数
    const randomNumber = randomInt(0, 1800) / 10000; // 生成一个0到1之间的随机浮点数
    console.log("概率：", probability, randomNumber, data.username)
    // 比较随机数和概率
    return randomNumber < probability;
}


module.exports = {
    startTask,
    realCornExecSingle
}

